import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {ActionSheetController, Content, Events, IonicPage, NavController} from 'ionic-angular';
import {ActivityStatus} from "../../../model/pages/activity/activity-filter/activity-filter.model";
import {LoadingService} from "../../../services/common/loading.service";
import * as _ from 'lodash';
import {TeamAddStaffProvider} from "../../../providers/my-team/team-add-staff/team-add-staff.provider";
import {TeamAddStaffDetailPage} from "../team-add-staff-detail/team-add-staff-detail";
import {TeamAddStaffFilterPage} from "../team-add-staff-filter/team-add-staff-filter";
import {TeamMarketActivityProvider} from "../../../providers/my-team/team-market-activity/team-market-activity.provider";
import {DateService} from "../../../services/common/date.service";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";

@IonicPage()
@Component({
    selector: 'page-team-add-staff-list',
    templateUrl: 'team-add-staff-list.html',
    providers: [
        TeamAddStaffProvider,
        LoadingService,
        DateService,
        TeamMarketActivityProvider
    ]
})
export class TeamAddStaffListPage {

    constructor(private navCtrl: NavController,
                private actionSheetCtrl: ActionSheetController,
                private events: Events,
                public changeRef: ChangeDetectorRef,
                private teamAddStaffProvider: TeamAddStaffProvider,
                private teamMarketActivityProvider: TeamMarketActivityProvider,
                private dateService: DateService,
                public adpActionSheet: AdpActionSheetController,
                private loadingService: LoadingService) {
    }

    @ViewChild(Content) content: Content;
    isScrolling = false;
    isArriveBottom = false;

    /**
     * 附加筛选条件变量（用作展示）
     */
    private tempFilter = {
        classify: 0,
        groupId: '',
        status: [1],
        startTime: this.dateService.getCurrentMonthFirstDay(),
        endTime: this.dateService.getCurrentMonthLastDay(),
    };

    private filter = {
        classify: 0,
        groupId: '',
        status: [1],
        startTime: this.dateService.getCurrentMonthFirstDay(),
        endTime: this.dateService.getCurrentMonthLastDay(),
    };

    private groupId: string = '';
    private groupName: string = '所有组';
    //客户活动组名称
    addStaffGroupTypes: Array<any> = [];

    /*增员列表数据*/
    private addStaffActivityList: Array<any> = [];

    /*合计数据*/
    addStaffTotal = {
        join: 0,
        notJoin: 0,
        preIcreaseNum: 0
    };

    ionViewDidLoad() {
        this.receiveFilterEvent();
        this.getAddStaffActivityList();
        this.getAddStaffGroupList();
    }

    ionViewWillLeave() {
        //this.resetFilter();
    }

    resetFilter() {
        this.tempFilter = {
            classify: 0,
            status: [1],
            startTime: this.dateService.getCurrentMonthFirstDay(),
            endTime: this.dateService.getCurrentMonthLastDay(),
            groupId: ''
        };
    }

    addStaffChange(item) {
        this.groupId = item.groupID;
        this.filter.groupId = item.groupID;
        this.getAddStaffActivityList();
    }

    /**
     * 取消订阅条件筛选
     */
    ionViewWillUnload() {
        this.events.unsubscribe('addStaff:search');
    }

    getAddStaffActivityList() {
        this.addStaffTotal = {
            join: 0,
            notJoin: 0,
            preIcreaseNum: 0
        };
        this.loadingService.showLoading();
        this.teamAddStaffProvider.getAddStaffActivityList(this.filter).subscribe((res) => {
            this.addStaffActivityList = res;
            res.forEach((item) => {
                item.isJoin = item.isJoin === '1' ? '是' : '否';
                this.addStaffTotal.join += parseInt(item.join || 0);
                this.addStaffTotal.notJoin += parseInt(item.notJoin || 0);
                this.addStaffTotal.preIcreaseNum += parseInt(item.preIcreaseNum || 0);

                if (!item.join && !item.notJoin && !item.preIcreaseNum) {
                    item.isShowDetail = false;
                }
            })
            this.loadingService.dismissLoading();
        }, e => {
            this.loadingService.dismissLoading();
        });
    }

    /*获取列表组数据*/
    getAddStaffGroupList() {
        this.teamMarketActivityProvider.getGroupList(this.filter, 3).subscribe((res) => {
            this.addStaffGroupTypes = [{groupID: "", groupName: "所有组"}].concat(res);
        });
    }

    openSelect() {
        let jobArray = [];
        this.addStaffGroupTypes.forEach((item) => {
            let obj = {};
            obj['text'] = item.groupName;
            obj['cssClass'] = this.groupId == item.groupID ? 'action-sheet-selected' : '';
            obj['value'] = item.groupID;
            obj['handler'] = () => {
                this.groupName = item.groupName;
                this.addStaffChange(item);
            };
            jobArray.push(obj);
        });
        this.adpActionSheet.create({
            title: '选择组',
            buttons: jobArray,
            cssClass: 'mySelect'
        }).present();
    }

    /**
     * 接收筛选条件
     */
    receiveFilterEvent() {
        let self = this;
        this.events.subscribe('addStaff:search',
            (filter) => {
                self.tempFilter = _.cloneDeep(filter);
                let cloneFilter = _.cloneDeep(filter);
                if (cloneFilter.status.length === 0) {
                    cloneFilter.status = [ActivityStatus.notStart, ActivityStatus.processing, ActivityStatus.over];
                }
                this.filter = cloneFilter;
                this.getAddStaffActivityList();
                this.getAddStaffGroupList();
            });
    }

    toFilterPage() {
        this.navCtrl.push('TeamAddStaffFilterPage', {
            filter: _.cloneDeep(this.tempFilter)
        });
    }

    goAddStaffActivityDetail(item) {
        if (!item.join && !item.notJoin && !item.preIcreaseNum) {
            return;
        }
        this.navCtrl.push('TeamAddStaffDetailPage', {
            id: item.id,
            groupId: this.groupId
        });
    }

    doRefresh(refresher) {
        this.getAddStaffActivityList();
        this.getAddStaffGroupList();
        setTimeout(() => {
            refresher.complete();
        }, 1000);
    }

    //滚动相关
    scrollStart() {
        this.isScrolling = true;
    }

    scrollEnd() {
        this.isScrolling = false;
    }

    scrolling() {
        const dimensions = this.content.getContentDimensions();
        const temp1 = dimensions.scrollHeight - dimensions.scrollTop - dimensions.contentHeight < 100;
        if (temp1 !== this.isArriveBottom) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }

    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }
}
